package cn.iocoder.yudao.module.wine.controller.admin.config;

import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.wine.controller.admin.config.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.config.WineConfigDO;
import cn.iocoder.yudao.module.wine.service.config.WineConfigService;

import java.time.LocalDateTime;

@Tag(name = "管理后台 - 平台配置")
@RestController
@RequestMapping("/wine/config")
@Validated
public class WineConfigController {

    @Resource
    private WineConfigService configService;


    @PutMapping("/update")
    @Operation(summary = "更新平台配置")
    @PreAuthorize("@ss.hasPermission('wine:config:update')")
    public CommonResult<Boolean> updateConfig(@Valid @RequestBody ConfigSaveReqVO updateReqVO) {
        if (updateReqVO.getIsOpenMonth() == 1 && updateReqVO.getFreeMonth() > 0) {
            LocalDateTime endTime = LocalDateTime.now().plusMonths(updateReqVO.getFreeMonth());
            updateReqVO.setCloseTime(endTime);
        } else {
            updateReqVO.setCloseTime(null);
        }
        configService.updateConfig(updateReqVO);
        return success(true);
    }


    @GetMapping("/get")
    @Operation(summary = "获得平台配置")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('wine:config:query')")
    public CommonResult<ConfigRespVO> getConfig() {
        WineConfigDO config = configService.getOne();
        return success(BeanUtils.toBean(config, ConfigRespVO.class));
    }

}
